﻿using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;

namespace BluetoothClient
{
    public partial class Program
    {
        private bool hasConnected = false;
        private const byte NOTE_SIZE = 2;
        private GT.Timer timer = new GT.Timer(4000);

        void ProgramStarted()
        {
            Debug.Print("Program Started");

            button.ButtonPressed += button_ButtonPressed;
            bluetooth.BluetoothStateChanged += bluetooth_BluetoothStateChanged;
            bluetooth.DataReceived += bluetooth_DataReceived;
            timer.Tick += timer_Tick;
        }

        void timer_Tick(GT.Timer timer)
        {
            bluetooth.ClientMode.Send("MESSAGE=<Hello from Gadgeteer>");
        }

        void bluetooth_DataReceived(Bluetooth sender, string data)
        {
            Debug.Print("Data Received by Gadgeteer: " + data);
        }

        void bluetooth_BluetoothStateChanged(Bluetooth sender, Bluetooth.BluetoothState btState)
        {
            if (btState == Bluetooth.BluetoothState.Connected)
            {
                Debug.Print("Bluetooth Connected");
                if (!hasConnected)
                    hasConnected = true;
                timer.Start();
            }
            else
            {
                Debug.Print("Bluetooth Not Connected");
                if (hasConnected)
                    this.Alarm();
                timer.Stop();
            }
        }

        void button_ButtonPressed(Button sender, Button.ButtonState state)
        {
            bluetooth.ClientMode.EnterPairingMode();
        }

        void Alarm()
        {
            // Alarm Sound
            for (int i = 0; i < NOTE_SIZE; ++i)
            {
                PlayNote(Tunes.Tone.C4, 200);
                PlayNote(Tunes.Tone.G4, 200);
            }

            tunes.Play();
        }

        void PlayNote(Tunes.Tone tone, int duration)
        {
            Tunes.MusicNote note = new Tunes.MusicNote(tone, duration);
            tunes.AddNote(note);
        }
    }
}
